﻿using Microsoft.EntityFrameworkCore;
using tju.cme.BookStore2024.webapi.Models.EF;
using tju.cme.BookStore2024.webapi.Models.ViewModels.ReaderNovel;

namespace tju.cme.BookStore2024.webapi.Services
{
    public class ReaderNovelServices(BookStore2024Context context)
    {
        /// <summary>
        /// 创建阅读记录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="readerId"></param>
        /// <returns></returns>
        public async Task ReadHistoryGreateAsync(ReadHistorylGreateModel model, Guid readerId)
        {
            var item = await context.T002readerNovels.FirstOrDefaultAsync(m => m.ReaderId == readerId && m.NovelId == model.NovelId);
            if (item != null) throw new Exception("该记录已存在");
            var newItem = new T002readerNovel()
            {
                Id = Guid.NewGuid(),
                ReaderId = readerId,
                NovelId = model.NovelId,
            };
            await context.T002readerNovels.AddAsync(newItem);
            await context.SaveChangesAsync();
        }

        /// <summary>
        /// 收藏或取消收藏小说
        /// </summary>
        /// <param name="recordId"></param>
        /// <param name="iscollect"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task IsCollectNovelAsync(Guid readerId , Guid novelId)
        {
            //var readernovel = await context.T002readerNovels.FindAsync(model.Id);
            var readernovel = await context.T002readerNovels.FirstOrDefaultAsync(m => m.ReaderId == readerId && m.NovelId == novelId);
            if (readernovel == null) throw new Exception("该记录不存在");
            readernovel.IsCollected = !readernovel.IsCollected;
            await context.SaveChangesAsync();
        }

        /// <summary>
        /// 根据读者ID获取阅读记录
        /// </summary>
        /// <param name="readerId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<V002readerNovelWithT001readerWithT031novelWithT011author>> GetAllRecordAsync(Guid readerId)
        {
            return await context.V002readerNovelWithT001readerWithT031novelWithT011authors.Where(m => m.ReaderId == readerId).ToListAsync();
        }
    }
}
